import threading

from common.manager.mqtt.mqtt_client_manager import MQTTClientManager
from common.utils.log_util import logger


class MQTTInitManager:
    mqtt_manager:MQTTClientManager = None
# 存储创建 MQTT 客户端的线程
    mqtt_thread: threading.Thread = None
    @staticmethod
    def create_client():
        mqtt_manager:MQTTClientManager = MQTTClientManager()
        # 创建 MQTT 客户端实例一
        # mqtt_manager.create_client("clientId1", "127.0.0.1", 1883, "admin", "123456")


        MQTTInitManager.mqtt_manager=mqtt_manager
        logger.info("MQTT 客户端创建完成")
        # 检查是否存在创建 MQTT 客户端实例的代码
        if  mqtt_manager.is_empty():
            MQTTInitManager.mqtt_manager.is_create = False
        logger.info("最后执行的MQTT客户端创建完成信息")

    @staticmethod
    def start_mqtt_creation():
        mqtt_thread = threading.Thread(target=MQTTInitManager.create_client)
        mqtt_thread.start()
        MQTTInitManager.mqtt_thread=mqtt_thread
        logger.info("MQTT 客户端创建线程已启动")

    @staticmethod
    def stop_mqtt_clients():
        if MQTTInitManager.mqtt_manager:
            # 假设 MQTTClientManager 类有一个 close_all_clients 方法用于关闭所有客户端
            MQTTInitManager.mqtt_manager.close_all()
            MQTTInitManager.mqtt_manager = None
            #提示关闭成功
            logger.info("MQTT 客户端已关闭")

    @staticmethod
    def stop_mqtt_thread():
        if MQTTInitManager.mqtt_thread and MQTTInitManager.mqtt_thread.is_alive():
            # 这里简单等待线程结束，更复杂的情况可能需要设置标志位来优雅退出
            MQTTInitManager.mqtt_thread.join()
            MQTTInitManager.mqtt_thread = None
            logger.info("MQTT 客户端创建线程已关闭")